package com.mxchip.livestarmobile.mobile.ui.login

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import com.mxchip.livestarmobile.mobile.MainActivity

import com.mxchip.livestarmobile.R
import com.mxchip.livestarmobile.mobile.base.toast
import com.mxchip.livestarmobile.mobile.rest.*
import com.mxchip.livestarmobile.mobile.state.AppConstant
import com.orhanobut.hawk.Hawk
import kotlinx.android.synthetic.main.verify_code_fragment.*

class VerifyCodeFragment : Fragment() {

    private val viewModel by activityViewModels<VerifyCodeViewModel>()

    private val args: VerifyCodeFragmentArgs by navArgs()

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.verify_code_fragment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val phoneNumber = args.phoneNumber
        var isEmail = false
        if (isEmail) {
            text_desc.text = "验证码已经发送到您的邮箱"
            text_phone_number.text = phoneNumber
        } else {
            text_phone_number.text = "+86 $phoneNumber"
        }


        viewModel.enableResend.observe(viewLifecycleOwner, Observer {
            if (it) {
                text_resend.setTextColor(ContextCompat.getColor(view.context, R.color.colorPrimary))
            } else {
                text_resend.setTextColor(ContextCompat.getColor(view.context, R.color.color_grey))
            }
        })

        viewModel.countDownInt.observe(viewLifecycleOwner, Observer {

            if (it > 0) {
                text_countdown.text = "$it s"
            } else {
                text_countdown.text = ""
            }
        })

        getCode(phoneNumber, isEmail)

        sms_code.setOnTextFinishListener { text, length ->

            val code = "" + text
            val loginType: String
            val hashMap: MutableMap<String, String> = hashMapOf()
            if (isEmail) {
                loginType = "verify_email_code"
                hashMap["email"] = phoneNumber
            } else {
                loginType = "verify_sms_code"
                hashMap["mobileNumber"] = phoneNumber
            }

            RestEndpoint.publicAPI.loginVerifyCode(code, hashMap, loginType).observe(viewLifecycleOwner, Observer { resp ->

                if (resp is ApiSuccessResponse) {
                    val data = resp.body

                    Hawk.put(AppConstant.SP_LOGIN_TOKEN, data.token)
                    Hawk.put(AppConstant.SP_LOGIN_PHONE_NUMBER, phoneNumber)
                    Hawk.put(AppConstant.SP_LOGIN_USER_ID, data.id)
                    val tokenMap: MutableMap<String, String> = hashMapOf()
                    val tokenType: String
                    if (isEmail) {
                        tokenType = "email_user"
                        tokenMap["email"] = phoneNumber
                    } else {
                        tokenType = "mobile_user"
                        tokenMap["mobileNumber"] = phoneNumber
                    }
                    LuxxEndpoint.luxxAPI.userToken(tokenType, tokenMap, 60 * 60 * 24 * 31).observe(viewLifecycleOwner, Observer { tokenResp ->

                        if (tokenResp is ApiSuccessResponse) {
                            val tokenData = tokenResp.body
                            Hawk.put(AppConstant.SP_LUXX_TOKEN, tokenData.token)
                            Hawk.put(AppConstant.SP_LUXX_NUMBER, tokenData.number)
                            Hawk.put(AppConstant.SP_LUXX_ROOM_ID, tokenData.roomId)

                            viewModel.login(phoneNumber, data.token, data.id)
                            startActivity(Intent(context, MainActivity::class.java))

                            activity?.finish()
                        }

                        if (tokenResp is ApiErrorResponse) {
                            toast(tokenResp.errorMessage)
                        }
                    })

                } else {
                    toast("验证码不匹配")
                }

            })
        }


        text_resend.setOnClickListener {

            val enable = viewModel.enableResend.value
            val countDownInt = viewModel.countDownInt.value

            if (enable != null && enable) {
                getCode(phoneNumber, isEmail)
            } else {
                toast("请在 $countDownInt 秒后重新尝试")
            }

        }
    }

    private fun getCode(phoneNumber: String, isEmail: Boolean) {

        viewModel.countDown()
        val sendCodeType: String
        val hashMap: MutableMap<String, String> = hashMapOf()
        if (isEmail) {
            sendCodeType = "send_email_code"
            hashMap["email"] = phoneNumber
        } else {
            sendCodeType = "send_sms_code"
            hashMap["mobileNumber"] = phoneNumber
        }

        RestEndpoint.publicAPI.loginSendCode(sendCodeType, hashMap).observe(viewLifecycleOwner, Observer { resp ->
            if (resp is ApiErrorResponse) {
                toast(resp.errorMessage)
            }
        })

    }


}
